package com.itheima.web.controller.store;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.store.Catalog;
import com.itheima.domain.store.Company;
import com.itheima.domain.store.Question;
import com.itheima.utils.BeanUtil;
import com.itheima.web.controller.BaseServlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;

@WebServlet("/store/question")
public class QuestionServlet extends BaseServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String operation = request.getParameter("operation");
        if("list".equals(operation)){
            //查询所有
            this.findAll(request,response);
        }else if("toAdd".equals(operation)){
            //跳转添加页面
            this.toAdd(request,response);
        }else if("save".equals(operation)){
            //添加信息
            try {
                this.save(request,response);
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
        }else if("toEdit".equals(operation)){
            //跳转编辑页面
            this.toEdit(request,response);
        }else if("edit".equals(operation)){
            //保存修改信息
            try {
                this.edit(request,response);
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
        }else if("delete".equals(operation)){
            //删除信息
            this.delete(request,response);
        }else if("downLoadReport".equals(operation)){
            //下载试题
            this.downLoadReport(request,response);
        }
    }

    private void downLoadReport(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
        String fileName = new String("测试文件.xlsx".getBytes(),"iso8859-1");
        response.addHeader("Content-Disposition","attachment;fileName="+fileName);
        ByteArrayOutputStream os = questionService.getReport();
        ServletOutputStream sos = response.getOutputStream();
        os.writeTo(sos);
        sos.flush();
        os.close();

    }

    private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {

        Question question = BeanUtil.fillBean(request, Question.class);
        questionService.delete(question);
        response.sendRedirect(request.getContextPath()+"/store/question?operation=list");
    }

    //保存修改信息
    //为什么update里有id?
    private void edit(HttpServletRequest request, HttpServletResponse response) throws IOException, FileUploadException {
        if(ServletFileUpload.isMultipartContent(request)){
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
            List<FileItem> fileItems = servletFileUpload.parseRequest(request);

            boolean flag = false;
            for (FileItem fileItem : fileItems) {
                if(StringUtils.isNotBlank(fileItem.getName())){
                    flag = true;
                    break;
                }
            }
            String realPath = getServletContext().getRealPath("upload");
            Question question = BeanUtil.fillBean(fileItems, Question.class);
            questionService.update(question,flag);
            for (FileItem item : fileItems) {
                try {
                    if(!item.isFormField()){
                        item.write(new File(realPath,question.getId()));
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        response.sendRedirect(request.getContextPath()+"/store/question?operation=list");
    }

    //跳转编辑页面
    private void toEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id =request.getParameter("id");
        Question question = questionService.findById(id);
        request.setAttribute("question",question);
        List<Company> companyList = companyService.findAll();
        request.setAttribute("companyList",companyList);
        List<Catalog> catalogList = catalogService.findAll();
        request.setAttribute("catalogList",catalogList);
        request.getRequestDispatcher("/WEB-INF/pages/store/question/update.jsp").forward(request,response);
    }


    //添加信息
    private void save(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, FileUploadException {
        if(ServletFileUpload.isMultipartContent(request)){
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
            List<FileItem> fileItems = servletFileUpload.parseRequest(request);

            boolean flag = false;
            for (FileItem fileItem : fileItems) {
                if(StringUtils.isNotBlank(fileItem.getName())){
                    flag = true;
                    break;
                }
            }
            String realPath = getServletContext().getRealPath("upload");
            Question question = BeanUtil.fillBean(fileItems, Question.class);
            String picture = questionService.save(question,flag);
            for (FileItem item : fileItems) {
                try {
                    if(!item.isFormField()){
                        item.write(new File(realPath,picture));
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        //QuestionService questionService =new QuestionServiceImpl();

        response.sendRedirect(request.getContextPath()+"/store/question?operation=list");


    }

    //跳转添加页面
    private void toAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Company> companyList = companyService.findAll();
        request.setAttribute("companyList",companyList);
        List<Catalog> catalogList = catalogService.findAll();
        request.setAttribute("catalogList",catalogList);
        request.getRequestDispatcher("/WEB-INF/pages/store/question/add.jsp").forward(request,response);
    }


    //查询所有
    private void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //QuestionService questionService =new QuestionServiceImpl();
        int page =1;
        int size =5;
        if(StringUtils.isNotBlank(request.getParameter("page"))){
            page = Integer.parseInt(request.getParameter("page"));
        }
        if(StringUtils.isNotBlank(request.getParameter("size"))){
            size = Integer.parseInt(request.getParameter("size"));
        }
        PageInfo all =questionService.findAll(page,size);
        request.setAttribute("page",all);
        request.getRequestDispatcher("/WEB-INF/pages/store/question/list.jsp").forward(request,response);
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
